package com.lwlk.zdk.Timer;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lwlk.zdk.annotation.JwtIgnore;
import com.lwlk.zdk.mapper.T.TDisEnterpriseMapper;
import com.lwlk.zdk.mapper.task.pwTaskEnterpriseAssessmentStatisticsMapper;
import com.lwlk.zdk.model.task.pwTaskEnterpriseAssessmentStatistics;
import com.lwlk.zdk.util.HttpClientUtils;
import com.lwlk.zdk.util.PropUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

//企业考核统计
@Component
@EnableScheduling

public class EnterpriseAssessmentTask {


    private final static String port = PropUtils.getString("ports");
    private final static String Ip = PropUtils.getString("Ip");
    private final static String clientCode = PropUtils.getString("clientCode");

    private static final Logger log = LoggerFactory.getLogger(EnterpriseAssessmentTask.class);

    @Autowired
    com.lwlk.zdk.mapper.pw.pwAssessGradeMapper pwAssessGradeMapper;
    @Autowired
    TDisEnterpriseMapper tDisEnterpriseMapper;
    @Autowired
    pwTaskEnterpriseAssessmentStatisticsMapper ptesMapper;

    @Scheduled(cron = "0 30 3 * * ?")//每天三点三十分执行


    public void data(){
        try {
            String time="2020-11-15";
            double netRateNumber=0;//入网率分数
            double onlineRateNumber=0;//上线率分数
            double trackFullRateNumber=0;//轨迹完整率分数
            double passRateNumber=0;//数据合格率分数
            double driftingRateNumber=0;//漂移率分数
            double overspeedCountNumber=0;//平均车辆超速次数分数
            double fatigueDrivingTimeNumber=0;//平均疲劳驾驶时长分数
            double connectRateNumber=0;//平台连通率分数
            double crossRateNumber=0;//跨域数据交换成功率分数
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            c.add(Calendar.DATE, -1);//-1.昨天时间 0.当前时间 1.明天时间 *以此类推
            //String time = sdf.format(c.getTime());
            Map map=new HashMap();
            map.put("date",time);//必传 数据产生时间yyyy-MM-dd
            Map<String,String>headMap=new HashMap<>();
            headMap.put("clientCode",clientCode);
            String url="http://"+Ip+":"+port+"/dis/assessment/enterprise/data";
            String result = HttpClientUtils.doGet(url,headMap,map);
            JSONObject json= JSONObject.parseObject(result);
            JSONArray jsonArray=json.getJSONArray("result");
            if (jsonArray==null){
                log.info(json.toJSONString());
            }
            String assessType="2";
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject=jsonArray.getJSONObject(i);
                String netRate=jsonObject.getString("netRate");//入网率
                String onlineRate=jsonObject.getString("onlineRate");//上线率
                String trackFullRate=jsonObject.getString("trackFullRate");//轨迹完整率
                String passRate=jsonObject.getString("passRate");//数据合格率
                String driftingRate=jsonObject.getString("driftingRate");//漂移率
                String overspeedCount=jsonObject.getString("overspeedCount");//平均车辆超速次数
                String fatigueDrivingTime=jsonObject.getString("fatigueDrivingTime");//平均疲劳驾驶时长
                String connectRate=jsonObject.getString("connectRate");//平台连通率
                String crossRate=jsonObject.getString("crossRate");//跨域数据交换成功率列表中有未创建的考核周期或考核类型的参数,请创建对应的考核评分规则
                String type=jsonObject.getString("type");//考核周期
                String eId=jsonObject.getString("eId");//企业id
                String TheInspectionTime=jsonObject.getString("createTime");//考核时间

                int count=pwAssessGradeMapper.selectByType(type,assessType);
                if (count==0){
                   log.info("列表中有未创建的考核周期或考核类型的参数,请创建对应的考核评分规则");
                }

                //获取企业名称
                String enterpriseName=tDisEnterpriseMapper.selectByEid(Integer.parseInt(eId));
                //获取企业所在地区
                List<Map<String, Object>> enterpriseList=tDisEnterpriseMapper.selectByEidList(Integer.parseInt(eId));
                String regionCode="";
                if (enterpriseList.size()==1){
                    regionCode= String.valueOf(enterpriseList.get(0).get("area_code"));
                }
                jsonObject.put("enterpriseName",enterpriseName);
                String assessPeriod =type.equals("0") ? "日考核" : (type.equals("1") ? "周考核" : type.equals("2") ? "月考核" : type.equals("3") ? "年考核" : null);
                jsonObject.put("assessPeriod",assessPeriod);

                //获取行政区划地

                /*wdHfArea wdHfArea=wdHfAreaMapper.selectByPrimaryKey(admdivcode);
                jsonObject.put("areaCode",wdHfArea.getName());*/


                NumberFormat nf = java.text.NumberFormat.getPercentInstance();
                nf.setMinimumFractionDigits(0);// 小数点后保留0位
                List<Map> assessGradeIdList=pwAssessGradeMapper.selectAssessGradeId(eId,assessType,type);//查询出此考核评分中有该企业的考核评分
                if (assessGradeIdList.size()==0){//当此企业没有在考核评分表中,描述中填写此企业未能参与考核评分
                    String describe=enterpriseName+"未能参与考核评分";
                    pwTaskEnterpriseAssessmentStatistics pwTaskEnterpriseAssessmentStatistics=new pwTaskEnterpriseAssessmentStatistics();
                    pwTaskEnterpriseAssessmentStatistics.seteId(Integer.parseInt(eId));
                    pwTaskEnterpriseAssessmentStatistics.setDescribe(describe);
                    pwTaskEnterpriseAssessmentStatistics.setEnterpriseName(enterpriseName);
                    pwTaskEnterpriseAssessmentStatistics.setType(Integer.parseInt(type));
                    pwTaskEnterpriseAssessmentStatistics.setTypeName(assessPeriod);
                    pwTaskEnterpriseAssessmentStatistics.setTheInspectionTime(TheInspectionTime);
                    pwTaskEnterpriseAssessmentStatistics.setStatus(2);
                    pwTaskEnterpriseAssessmentStatistics.setRegionCode(regionCode);

                    int eidNull=ptesMapper.insertSelective(pwTaskEnterpriseAssessmentStatistics);
                    continue;
                }
                for (int j = 0; j < assessGradeIdList.size(); j++) {
                    //计算入网率得分
                    String indexName="0";//车辆入网率
                    List<Map<String,Object>> assessGrade=pwAssessGradeMapper.selectAssessGrade(Integer.parseInt(String.valueOf(assessGradeIdList.get(j).get("id"))),indexName);//入网率参数
                    Double netRateNum=Double.valueOf(netRate);//将入网率转成double
                    String RuWangLv = nf.format(netRateNum);//车辆入网率转成百分数
                    if (assessGrade.size()>0){
                        if (assessGrade.size()>0){
                            String s=RuWangLv.replace("%","");
                            if (Integer.parseInt(s)<Integer.parseInt(String.valueOf(assessGrade.get(0).get("lowestMarkRatio")))){//如果入网率低于指标,不得分

                            }else {
                                netRateNumber=netRateNum*Integer.parseInt(String.valueOf(assessGrade.get(0).get("score")));//入网率得分
                                BigDecimal bn = new BigDecimal(netRateNumber);
                                netRateNumber = bn.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                            }
                        }else {
                            netRateNumber=0;
                        }
                    }



                    //计算上线率分数
                    Double onlineRateNum=Double.valueOf(onlineRate);//将上线率转成double
                    String indexNameOnline="1";//车辆上线率
                    String OnlineRate=nf.format(onlineRateNum);//上线率转成百分数
                    List<Map<String,Object>> assessGradeOnline=pwAssessGradeMapper.selectAssessGrade(Integer.parseInt(String.valueOf(assessGradeIdList.get(j).get("id"))),indexNameOnline);//上线率参数
                    if (assessGradeOnline.size()>0){
                        if (assessGradeOnline.size()>0){
                            onlineRateNumber=onlineRateNum*Integer.parseInt(String.valueOf(assessGradeOnline.get(0).get("score")));//上线率得分
                            BigDecimal bn = new BigDecimal(onlineRateNumber);
                            onlineRateNumber = bn.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        }else {
                            onlineRateNumber =0;
                        }

                    }


                    //计算轨迹完整率分数
                    String indexNameTrack="2";//轨迹完整率
                    List<Map<String,Object>> assessGradeTrack=pwAssessGradeMapper.selectAssessGrade(Integer.parseInt(String.valueOf(assessGradeIdList.get(j).get("id"))),indexNameTrack);//轨迹完整率参数
                    Double trackFullRateNum=Double.valueOf(trackFullRate);//将轨迹完整率转成double
                    String TrajectoryIntegrityRate = nf.format(trackFullRateNum);//轨迹完整率转成百分数
                    if (assessGradeTrack.size()>0){
                        if (assessGradeTrack.size()>0){
                            String track=TrajectoryIntegrityRate.replace("%","");
                            if (Integer.parseInt(track)<=Integer.parseInt(String.valueOf(assessGradeTrack.get(0).get("lowestMarkRatio")))){//如果轨迹完整率低于指标,不得分
                                trackFullRateNumber=0;
                            }else {
                                trackFullRateNumber=trackFullRateNum*Integer.parseInt(String.valueOf(assessGradeTrack.get(0).get("score")));//轨迹完整率得分
                                BigDecimal trackBig = new BigDecimal(trackFullRateNumber);
                                trackFullRateNumber = trackBig.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                            }
                        }else {
                            trackFullRateNumber=0;
                        }
                    }



                    //计算数据合格率分数
                    String indexNamePass="3";//数据合格率
                    List<Map<String,Object>> assessGradePass=pwAssessGradeMapper.selectAssessGrade(Integer.parseInt(String.valueOf(assessGradeIdList.get(j).get("id"))),indexNamePass);//轨迹完整率参数
                    Double passRateNum=Double.valueOf(passRate);//将数据合格率转成double
                    String DataPassRate = nf.format(passRateNum);//数据合格率转成百分数
                    if (assessGradePass.size()>0){
                        if (assessGradePass.size()>0){
                            String passRateInt=DataPassRate.replace("%","");
                            if (Integer.parseInt(passRateInt)<=Integer.parseInt(String.valueOf(assessGradePass.get(0).get("lowestMarkRatio")))){//如果数据合格率低于指标,不得分
                                passRateNumber=0;
                            }else {
                                passRateNumber=passRateNum*Integer.parseInt(String.valueOf(assessGradePass.get(0).get("score")));//数据合格率得分
                                BigDecimal trackBig = new BigDecimal(passRateNumber);
                                passRateNumber = trackBig.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                            }
                        }else {
                            passRateNumber=0;
                        }
                    }



                    //计算漂移率分数
                    String indexNameDrifting="4";//漂移率
                    List<Map<String,Object>> assessGradeDrifting=pwAssessGradeMapper.selectAssessGrade(Integer.parseInt(String.valueOf(assessGradeIdList.get(j).get("id"))),indexNameDrifting);//漂移率参数
                    Double driftingNum=Double.valueOf(driftingRate);//将漂移率转成double
                    String driftRate = nf.format(driftingNum);//漂移率转成百分数
                    if (assessGradeDrifting.size()>0){
                        if (assessGradeDrifting.size()>0){
                            String driftingInt=driftRate.replace("%","");
                            if (Integer.parseInt(driftingInt)<=Integer.parseInt(String.valueOf(assessGradeDrifting.get(0).get("lowestMarkRatio")))){//如果漂移率低于指标,不得分
                                driftingRateNumber=0;
                            }else {
                                driftingRateNumber=driftingNum*Integer.parseInt(String.valueOf(assessGradeDrifting.get(0).get("score")));//漂移率得分
                                BigDecimal trackBig = new BigDecimal(driftingRateNumber);
                                driftingRateNumber = trackBig.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                            }

                        }
                    }


                    //计算平均车辆超速次数分数
                    String indexNameOverspeedCount="5";//平均车辆超速次数
                    List<Map<String,Object>> assessGradeOverspeedCount=pwAssessGradeMapper.selectAssessGrade(Integer.parseInt(String.valueOf(assessGradeIdList.get(j).get("id"))),indexNameOverspeedCount);//平均车辆超速次数参数
                    Double overspeedCountNum=Double.valueOf(overspeedCount);//将平均车辆超速次数转成double
                    String overspeed = nf.format(overspeedCountNum);//平均车辆超速次数转成百分数
                    String overspeedInt=overspeed.replace("%","");
                    if (assessGradeOverspeedCount.size()>0){
                        if (assessGradeOverspeedCount.size()>0){
                            if (Integer.parseInt(overspeedInt)<Integer.parseInt(String.valueOf(assessGradeOverspeedCount.get(0).get("lowestMarkRatio")))){//如果平均车辆超速次数低于指标 算法:10+(指标 - 平均车速次数)/指标 * 10
                                overspeedCountNumber=10+(Integer.parseInt(String.valueOf(assessGradeOverspeedCount.get(0).get("lowestMarkRatio")))-Integer.parseInt(overspeedInt))/Integer.parseInt(String.valueOf(assessGradeOverspeedCount.get(0).get("lowestMarkRatio")))*10;
                            }else if (Integer.parseInt(overspeedInt)>Integer.parseInt(String.valueOf(assessGradeOverspeedCount.get(0).get("lowestMarkRatio"))) && Integer.parseInt(overspeedInt)<Integer.parseInt(String.valueOf(assessGradeOverspeedCount.get(0).get("lowestMarkRatio")))*2){//如果平均车辆超速次数高于指标并小于指标的2倍
                                overspeedCountNumber=(Integer.parseInt(String.valueOf(assessGradeDrifting.get(0).get("score")))*2-overspeedCountNum)/Integer.parseInt(String.valueOf(assessGradeDrifting.get(0).get("score")))*10;//平均车辆超速次数得分
                                BigDecimal trackBig = new BigDecimal(overspeedCountNumber);
                                overspeedCountNumber = trackBig.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();//四舍五入
                            }else if (Integer.parseInt(overspeedInt)>Integer.parseInt(String.valueOf(assessGradeOverspeedCount.get(0).get("lowestMarkRatio")))*2){//如果平均车辆超速次数大于指标的2倍,不得分
                                overspeedCountNumber=0;
                            }
                        }else {
                            overspeedCountNumber=0;
                        }
                    }



                    //计算平均疲劳驾驶时长分数
                    String indexNameFatigueDriving="6";//平均疲劳驾驶时长
                    List<Map<String,Object>> assessGradeFatigueDriving=pwAssessGradeMapper.selectAssessGrade(Integer.parseInt(String.valueOf(assessGradeIdList.get(j).get("id"))),indexNameFatigueDriving);//平均疲劳驾驶时长参数
                    Long ff=Long.valueOf(fatigueDrivingTime);//将平均疲劳驾驶时长转成Long
                    String FatigueDrivingTime=String.valueOf(ff);//平均疲劳驾驶时长
                    if (assessGradeFatigueDriving.size()>0){
                        if (assessGradeFatigueDriving.size()>0){
                            if (ff.longValue()<Long.valueOf(String.valueOf(assessGradeFatigueDriving.get(0).get("lowestMarkRatio"))).longValue()){//如果平均疲劳驾驶时长低于指标,算法:10+(指标 - 平均疲劳驾驶时长)/指标 * 10
                                fatigueDrivingTimeNumber=10+(Integer.parseInt(String.valueOf(assessGradeFatigueDriving.get(0).get("score")))-Integer.parseInt(overspeedInt))/Integer.parseInt(String.valueOf(assessGradeFatigueDriving.get(0).get("score")))*10;
                                BigDecimal trackBig = new BigDecimal(fatigueDrivingTimeNumber);
                                fatigueDrivingTimeNumber = trackBig.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                            }else if (ff.longValue()>Long.valueOf(String.valueOf(assessGradeFatigueDriving.get(0).get("lowestMarkRatio")))*2){//如果平均疲劳驾驶时长大于指标的2倍,不得分
                                fatigueDrivingTimeNumber=0;
                            }
                            else if (ff.longValue()>Long.valueOf(String.valueOf(assessGradeFatigueDriving.get(0).get("lowestMarkRatio")))&&ff.longValue()<Long.valueOf(String.valueOf(assessGradeFatigueDriving.get(0).get("lowestMarkRatio")))*2){
                                fatigueDrivingTimeNumber=(Long.valueOf(String.valueOf(assessGradeFatigueDriving.get(0).get("score")))*2-ff)/Long.valueOf(String.valueOf(assessGradeFatigueDriving.get(0).get("score")))*10;//平均疲劳驾驶时长得分
                                BigDecimal trackBig = new BigDecimal(fatigueDrivingTimeNumber);
                                fatigueDrivingTimeNumber = trackBig.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                            }
                        }else {
                            fatigueDrivingTimeNumber=0;
                        }
                    }



                    //计算平台连通率分数
                    String indexNameConnect="7";//平台连通率
                    List<Map<String,Object>> assessGradeConnect=pwAssessGradeMapper.selectAssessGrade(Integer.parseInt(String.valueOf(assessGradeIdList.get(j).get("id"))),indexNameConnect);//平台连通率参数
                    Double connectRateNum=Double.valueOf(connectRate);//将平台连通率转成double
                    String connect = nf.format(connectRateNum);//平台连通率转成百分数
                    if (assessGradeConnect.size()>0){
                        if (assessGradeConnect.size()>0){
                            String connectInt=connect.replace("%","");
                            if (Integer.parseInt(connectInt)>Integer.parseInt(String.valueOf(assessGradeConnect.get(0).get("lowestMarkRatio")))){
                                connectRateNumber=connectRateNum*Integer.parseInt(String.valueOf(assessGradeConnect.get(0).get("score")));
                                BigDecimal trackBig = new BigDecimal(connectRateNumber);
                                connectRateNumber = trackBig.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                            }else {
                                connectRateNumber=0;
                            }
                        }else {
                            connectRateNumber=0;
                        }
                    }



                    //计算跨域数据交换成功率分数
                    String indexNameCross="8";//跨域数据转发
                    List<Map<String,Object>> assessGradeCross=pwAssessGradeMapper.selectAssessGrade(Integer.parseInt(String.valueOf(assessGradeIdList.get(j).get("id"))),indexNameCross);//跨域数据交换成功率参数
                    Double crossRateNum=Double.valueOf(crossRate);//将跨域数据交换成功率转成double
                    String CrossDomainData = nf.format(crossRateNum);//跨域数据交换成功率转成百分数
                    if (assessGradeCross.size()>0){
                        if (assessGradeCross.size()>0){
                            String crossInt=CrossDomainData.replace("%","");
                            if (Integer.parseInt(crossInt)>Integer.parseInt(String.valueOf(assessGradeCross.get(0).get("lowestMarkRatio")))){
                                crossRateNumber=crossRateNum*Integer.parseInt(String.valueOf(assessGradeCross.get(0).get("score")));
                                BigDecimal trackBig = new BigDecimal(crossRateNumber);
                                crossRateNumber = trackBig.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                            }else {
                                crossRateNumber=0;
                            }
                        }else {
                            crossRateNumber=0;
                        }
                    }


                    double GrossScore=netRateNumber+onlineRateNumber+trackFullRateNumber+passRateNumber+driftingRateNumber+overspeedCountNumber+fatigueDrivingTimeNumber+connectRateNumber+crossRateNumber;

                    pwTaskEnterpriseAssessmentStatistics pteas=new pwTaskEnterpriseAssessmentStatistics();
                    pteas.setAssessGradeId(Integer.parseInt(String.valueOf(assessGradeIdList.get(j).get("id"))));
                    pteas.seteId(Integer.parseInt(eId));
                    pteas.setGrossScore(GrossScore);
                    pteas.setEnterpriseName(enterpriseName);
                    pteas.setNetRateNumber(netRateNumber);
                    pteas.setOnlineRateNumber(onlineRateNumber);
                    pteas.setTrackFullRateNumber(trackFullRateNumber);
                    pteas.setPassRateNumber(passRateNumber);
                    pteas.setDriftingRateNumber(driftingRateNumber);
                    pteas.setOverspeedCountNumber(overspeedCountNumber);
                    pteas.setFatigueDrivingTimeNumber(fatigueDrivingTimeNumber);
                    pteas.setConnectRateNumber(connectRateNumber);
                    pteas.setCrossRateNumber(crossRateNumber);
                    pteas.setType(Integer.parseInt(type));
                    pteas.setTypeName(assessPeriod);
                    pteas.setDescribe(enterpriseName+"成功参与考核评分");
                    pteas.setTheInspectionTime(TheInspectionTime);
                    pteas.setRuWangLv(RuWangLv);
                    pteas.setOnlineRate(OnlineRate);
                    pteas.setTrajectoryIntegrityRate(TrajectoryIntegrityRate);
                    pteas.setDataPassRate(DataPassRate);
                    pteas.setDriftRate(driftRate);
                    pteas.setOversPeed(overspeedInt);
                    pteas.setFatigueDrivingTime(FatigueDrivingTime);
                    pteas.setConnect(connect);
                    pteas.setCrossDomainData(CrossDomainData);
                    pteas.setStatus(1);
                    pteas.setRegionCode(regionCode);
                    int ptes=ptesMapper.insertSelective(pteas);

                    //jsonObject.put("GrossScore",GrossScore);
                }
                for (int j = 0; j < assessGradeIdList.size(); j++) {
                    Integer id =Integer.parseInt(String.valueOf(assessGradeIdList.get(j).get("id")));
                    List<Map<String,Object>>cityAndCountyList=ptesMapper.selectStatus(id,TheInspectionTime,assessPeriod);//根据考核方案考核时间考核周期名称
                    for (int k = 0; k < cityAndCountyList.size(); k++) {
                        int rank=k+1;
                        int pId= Integer.parseInt(String.valueOf(cityAndCountyList.get(k).get("id")));
                        int sum=ptesMapper.updateRanking(pId,rank);
                    }
                }
                log.info("执行完成");

            }
            //return json;

        }catch (Exception e){
            e.printStackTrace();
        }
        //return null;
    }
}
